<template>
  <div class="three-tif" ref="tifRef"></div>
</template>

<script setup>
import { ref, onMounted } from "vue";

// 导入 Three
import * as THREE from "three";

// 导入TTIFLoader 加载器
import { TIFFLoader } from "three/examples/jsm/loaders/TIFFLoader.js";

// 获取 dom
const tifRef = ref();

let renderer, scene, camera;

// 初始化
function init() {
  // 创建相机
  camera = new THREE.PerspectiveCamera(
    45,
    tifRef.value.clientWidth / tifRef.value.clientHeight,
    0.01,
    10
  );
  camera.position.set(0, 0, 4);

  // 创建渲染器
  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(tifRef.value.clientWidth, tifRef.value.clientHeight);
  tifRef.value.appendChild(renderer.domElement);

  // 创建场景
  scene = new THREE.Scene();

  // 创建 TTIF 加载器
  const loader = new TIFFLoader();

  // 创建平面
  const geometry = new THREE.PlaneGeometry();

  // 加载 tif 文件 应用纹理
  loader.load("/crate_uncompressed.tif", function (texture) {
    texture.colorSpace = THREE.SRGBColorSpace;
    const material = new THREE.MeshBasicMaterial({ map: texture });

    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(-1.0, -1.1, 0);
    scene.add(mesh);

    // 渲染
    render();
  });

  // LZW
  loader.load("/crate_lzw.tif", function (texture) {
    texture.colorSpace = THREE.SRGBColorSpace;

    const material = new THREE.MeshBasicMaterial({ map: texture });

    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(0, 0, 0);

    scene.add(mesh);

    render();
  });

  // RLE
  loader.load("/rjy.tif", function (texture) {
    texture.colorSpace = THREE.SRGBColorSpace;

    const material = new THREE.MeshBasicMaterial({ map: texture });

    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(0.98, 1.05, 0);

    scene.add(mesh);

    render();
  });
}

function onWindowResize() {
  camera.aspect = tifRef.value.clientWidth / tifRef.value.clientHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(tifRef.value.clientWidth, tifRef.value.clientHeight);

  render();
}

function render() {
  renderer.render(scene, camera);
}

onMounted(() => {
  init();

  window.addEventListener("resize", onWindowResize);
});
</script>

<style scoped>
.three-tif {
  width: 50%;
  height: 100%;
}
</style>
